<?php

namespace Application\Site1Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;



class AclController extends Controller
{
    /**
     *
     * @return \Doctrine\ORM\EntityManager
     */
    private function getEntityManager()
    {
        return $this->container->getDoctrine_ORM_EntityManagerService();
    }
    /**
     * @return \Bundle\AclBundle\Acl
     */
    private function getAcl()
    {
        return $this->container->getAclService();
    }

    /**
     * @return \Symfony\Components\Templating\Engine
     */
    private function getRender()
    {
        return $this->container->getTemplatingService();
    }

    private function loadAcl()
    {
        $em = $this->getEntityManager();
        $roles = $em->getRepository('Application\\Site1Bundle\\Entities\\Role')->findAll();

        foreach($roles as $role)
        {
            $this->getAcl()->addRole($role,$role->getParent());
        }

        $resources = $em->getRepository('Application\\Site1Bundle\\Entities\\Resource')->findAll();

        foreach($resources as $resource)
        {
            $this->getAcl()->addResource($resource, $resource->getParent());
        }

        $rights = $em->getRepository('Application\\Site1Bundle\\Entities\\Right')->findAll();

        foreach($rights as $right)
        {
            if($right->getAllowed())
                $this->getAcl()->allow($right->getRole(), $right->getResource(), $right->getAction());
            else
                $this->getAcl()->deny($right->getRole(), $right->getResource(), $right->getAction());
        }

    }

    public function viewAction()
    {
        $this->loadAcl();
        $actions = array(
            'create', 'read', 'update', 'delete'
        );
        
        $content = '';

        foreach($this->getAcl()->getRoles() as $role)
        {
            $result = array();

            foreach($this->getAcl()->getResources() as $resource)
            {
                $result [] = $this->getAcl()->
                        isAllowed($role, $resource, null);
            }

            $content .= $this->getRender()->render('Site1Bundle:Acl:rightbit', array('rights' => $result,
                'role' => $role));
        }

        return $this->render('Site1Bundle:Acl:index', array(
            'roles'     => $this->getAcl()->getRoles(),
            'resources' => $this->getAcl()->getResources(),
            'content'    => $content));
    }
}
